/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& prev_i, int inorder_begin, int inorder_end){
        if(inorder_begin > inorder_end)
            return nullptr;
        
        // 1.前序确定根
        // 2.中序确定左子树和右子树
        // 3.通过控制边界递归构建左右子树

        TreeNode *root = new TreeNode(preorder[prev_i]);

        // 找到root_i划分中序的左右子树
        int root_i = inorder_begin;
        while(root_i <= inorder_end)
        {
            if(inorder[root_i] == preorder[prev_i])
                break;
            else
                root_i++;
        }
        // [inorder_begin, root_i] root_i [root_i + 1, inorder_end]

        // [inorder_begin, root_i]  ---  左子树
        if(inorder_begin <= root_i - 1)
            root->left = _buildTree(preorder, inorder, ++prev_i, inorder_begin, root_i - 1);
        else
            root->left = nullptr;

        // [root_i + 1, inorder_end]  ---  右子树
        if(root_i + 1 <= inorder_end)
            root->right = _buildTree(preorder, inorder, ++prev_i, root_i + 1, inorder_end);
        else
            root->right = nullptr;

        // 注意:这里prev_i不能用后置++传递

        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int prev_i = 0;

        int inorder_begin = 0;
        int inorder_end = inorder.size() - 1;

        return _buildTree(preorder, inorder, prev_i, inorder_begin, inorder_end);
    }
};